package com.chengliang.bbs.util;

import com.chengliang.bbs.entry.User;
import com.chengliang.bbs.entry.UserAuths;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;

/**
 * @author: chengliang
 * @create: 2019-07-29 09:38
 */
public class UserUtils {

    public static final String ADMIN_NAME="ROLE_admin";

    /**
     * 修改当前用户认证状态
     * @param ifverified
     */
    public static void updateCurrAuthsIfverified(Integer ifverified){
        currentUser().setUserIfverified(ifverified);
    }

    /**
     * 获取当前用户授权信息
     * @return
     */
    public static UserAuths currentUser(){
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //该用户未登陆
        if(principal.equals("anonymousUser")){
            return null;
        }
        return (UserAuths) principal;
    }

    /**
     * 当前用户是否是管理员
     * @return
     */
    public static boolean isNotAdmin(){
        return !SecurityContextHolder.getContext().getAuthentication().getAuthorities().toString().contains(ADMIN_NAME);
    }

    /**
     * @param user
     * 修改session中的当前用户信息
     */
    public static void updateAuthsCurrUser(User user){
        if(user==null){
            return;
        }
        //原信息
        User currUser = currentUser().getUser();
        //邮箱
        if(!StringUtils.isEmpty(user.getUserEmail())){
            currUser.setUserEmail(user.getUserEmail());
        }
        //昵称
        if(!StringUtils.isEmpty(user.getUserNickName())){
            currUser.setUserNickName(user.getUserNickName());
        }
        //签名
        if(!StringUtils.isEmpty(user.getUserSign())){
            currUser.setUserSign(user.getUserSign());
        }
        //城市
        if(!StringUtils.isEmpty(user.getUserAddress())){
            currUser.setUserAddress(user.getUserAddress());
        }
        //性别
        if(!StringUtils.isEmpty(user.getUserSex())){
            currUser.setUserSex(user.getUserSex());
        }
        //头像
        if(!StringUtils.isEmpty(user.getUserAvatar())){
            currUser.setUserAvatar(user.getUserAvatar());
        }

    }

}
